<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="item in quickSearchData"
        :key="item.key"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">{{ item.label }}</div>
        <div class="quick-search-item-value" :class="[item.checked ? 'quick-search-item-value-checked' : '']">{{ item.value }}</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="initLoadData" @reset="searcherReset" />
    <div class="table-summary-box">
      <div class="table-info">
        <span class="table-info-item">
          已消费金额：<span class="num">{{ unitVal(headerConfig?.companyConsumeAmount, '元') }}</span>
        </span>
        <span class="table-info-item">
          账户余额：<span class="num">{{ unitVal(headerConfig?.accountBalance, '元') }}</span>
        </span>
        <span class="table-info-item">
          企业合同收费标准：<span class="num">{{ unitVal(headerConfig?.companyContractChargeAmount, '元') }}</span>
        </span>
        <span class="table-info-item">
          个人合同收费标准：<span class="num">{{ unitVal(headerConfig?.personContractChargeAmount, '元') }}</span>
        </span>
      </div>
      <a-alert>
        <template #icon>
          <icon-exclamation-circle />
        </template>
        <div>合同扣费说明：</div>
        <div>1. 当合同状态变更为：签署中且双方未签署时，会预先扣费，如此时撤回合同不再签署，则不收取费用</div>
        <div>2. 当合同状态变更为：签署中(一方已签署)、已完成、已撤回(一方已签署)、作废中、已作废时，收取费用</div>
        <div>3. 合同生成后，修改租车费/续租费/换车费/租车押金/违章押金后，不影响已发起签署的合同金额</div>
      </a-alert>
    </div>
    <table-index :table="table" @loadData="loadData">
      <template #orderCode="{ record }">
        <template v-if="record.orderCode">
          <a-link type="link" @click="() => onLink(record)" style="color: rgba(24, 144, 255, 1); text-decoration: underline">
            {{ record.orderCode }}
          </a-link>
        </template>
        <div v-else>-</div>
      </template>

      <template #lesseeName="{ record }">
        <div v-if="record.leaseType === 2">{{ record.lesseeName || '-' }}</div>
        <div v-else>
          <div>{{ record.lesseeCompanyName || '-' }}</div>
          <!-- <div>承租人：{{ record.lesseeName || '-' }}</div> -->
        </div>
      </template>

      <template #contractStatus="{ record }">
        <div class="status" :class="getClassName(record)">{{ record.contractStatusName }}</div>
        <!-- 生成失败 -->
        <a-button type="primary" size="mini" v-if="record.contractStatus == -1" @click="errorShow(record)">原因</a-button>
        <!-- 2: 签署中 3：已完成 7：作废中 8：已作废 -->
        <template v-if="[2, 3, 7, 8].includes(Number(record.contractStatus))">
          <div>
            承租方：
            <!-- 签署中 -->
            <span
              class="block"
              v-if="[2, 3, 8].includes(Number(record.contractStatus))"
              :class="record.lesseeSignStatus === 1 ? 'block-unsign' : 'block-signed'"
            >
              {{ record.lesseeSignStatusName }}
            </span>
            <!-- 作废中 -->
            <span
              class="block"
              v-if="record.contractStatus == 7"
              :class="record.lesseeInvalidedStatus === 1 ? 'block-unsign' : 'block-signed'"
            >
              {{ record.lesseeInvalidedStatusName }}
            </span>

            <a-button
              type="text"
              size="mini"
              @click="onCopy(record, '已将链接复制到剪切板')"
              v-permission="'svms:business:contract:sign.contractCopySigningLink'"
              v-if="(record.orderType === 1 || record.orderType === 2) && [2, 3, 8].includes(Number(record.contractStatus))"
            >
              <template #icon>
                <icon-link />
              </template>
              复制合同链接
            </a-button>

            <a-button
              type="text"
              size="mini"
              @click="onCopy(record, '承租方作废链接已复制到剪切板')"
              v-permission="'svms:business:contract:sign.contractCopyVoidLink'"
              v-if="(record.orderType === 1 || record.orderType === 2) && record.lesseeInvalidedStatus == 1 && record.contractStatus == 7"
            >
              <template #icon>
                <icon-link />
              </template>
              复制作废链接
            </a-button>
          </div>
          <div>
            出租方：
            <span
              class="block"
              v-if="[2, 3, 8].includes(Number(record.contractStatus))"
              :class="record.hireSignStatus === 1 ? 'block-unsign' : 'block-signed'"
            >
              {{ record.hireSignStatusName }}
            </span>
            <span
              class="block"
              v-if="record.contractStatus === 7"
              :class="record.hireInvalidedStatus === 1 ? 'block-unsign' : 'block-signed'"
            >
              {{ record.hireInvalidedStatusName }}
            </span>
          </div>
        </template>
      </template>

      <template #finishTime="{ record }">
        <div>承租方：{{ record.lesseeSignTime || '-' }}</div>
        <div>出租方：{{ record.hireSignTime || '-' }}</div>
      </template>
    </table-index>
  </div>
  <!-- 更换车牌 -->
  <AddPhone ref="addPhonesRef" @ok="addphoneFn" />
  <!-- 去签署/去作废 -->
  <OpenLink ref="openLinksRef" @ok="openlinkFn" />
  <!-- 完善信息 -->
  <ImproveInformationModal :type="type" :modal-alert="modalAlert" ref="improveInformationRef" />
  <!-- 生成电子合同 -->
  <ViewContractModal v-model:visible="viewVisible" v-model:loading="viewLoading" :order="orderDetails" @on-ok="onOk" />
  <!-- 预览pdf -->
  <pdf-viewer
    :url="pdfViewInfo.url"
    :title="pdfViewInfo.title"
    v-model:visible="pdfViewInfo.show"
    @close="Object.assign(pdfViewInfo, { ...PDFDefaultAttr })"
  />
</template>

<script setup lang="ts">
  import { ref, computed, reactive, onMounted } from 'vue'

  import ImproveInformationModal from '@/views/order/modals/improve-information-modal.vue'
  import ViewContractModal from '@/views/order/modals/view-contract-modal.vue'
  import AddPhone from '@/views/order/short-order/detail/components/add-phone.vue'
  import OpenLink from '@/views/order/short-order/detail/components/open-link.vue'

  import { useExport } from '@/hooks/list'
  import { unitVal } from '@/utils'
  import { useFetchTableDataApi, useTable } from '@/hooks/table'
  import useClipboard from 'vue-clipboard3'
  import { Message, Modal } from '@arco-design/web-vue'
  import {
    getContractSignRecord,
    getContractTenantSignUrl,
    exportContractAuthRecord,
    contractSignRecordHeader,
    contractSignRecordCount,
  } from '@/api/business/contract'
  import { usePageDict } from '@/hooks/useDict'
  import request from '@/api/axios.config'
  import {
    invalidAPI,
    determineAPI,
    revokeAPI,
    nullifyAPI,
    initiateAPI,
    getTenantSignUrlAPI,
    createQysContractAPI,
    getShortOrdrDetails,
    createContractAPI,
  } from '@/api/order/sOrder'
  import { getDetail, clientupdate } from '@/api/market/clientInfo'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'
  import { isMobile } from '@/utils/validate'

  // pdf预览
  import { PDFDefaultAttr } from '@/components/pdf-viewer/const'
  const pdfViewInfo = reactive({ ...PDFDefaultAttr })

  const userStore = useUserStore() as any
  userStore.setEpDetail()
  const pageDict = usePageDict('systemParamDict')
  console.log(pageDict, 'pageDict')
  console.log(userStore, 'userStore')

  const { navigateTo } = useNavigate()
  const type = ref('person')
  const modalAlert = ref('')
  const viewVisible = ref(false)
  const viewLoading = ref(false)
  const addPhonesRef = ref()
  const openLinksRef = ref()
  const clientData = ref() //企业联系人信息
  const { toClipboard } = useClipboard()
  const quickSearchData = ref([
    {
      key: 1,
      label: '未发起合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 2,
      label: '签署中合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 7,
      label: '作废中合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 3,
      label: '已完成合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 5,
      label: '已撤回合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 8,
      label: '已作废合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 6,
      label: '已截止签署合同数(份)',
      value: 0,
      checked: false,
    },
  ])

  const quickSearchClick = (item: any) => {
    quickSearchData.value.forEach((i: any) => {
      i.checked = false
    })
    item.checked = true
    queryParam.contractStatusList = [item.key]
    loadData(1)
    getContractSignRecordHeader()
  }

  const getClassName = (record: any) => {
    switch (record.contractStatus) {
      case 1:
        return 'status-unauth'
      case 2:
        return 'status-signing'
      case 3:
      case 10:
        return 'status-success'
      case 4:
      case 5:
      case -1:
      case 6:
      case 8:
      case 11:
        return 'status-finish'
      case 7:
        return 'status-failed'
      case 9:
        return 'status-invalid'
    }
  }

  const queryParam = reactive<any>({
    createTimeRange: [],
    dateRange: [],
    payType: 1,
  })
  const searchList = computed(() => {
    return [
      { label: '合同编号', prop: 'contractNo', type: 'a-input', maxlength: 30 },
      { label: '关联订单编号', prop: 'orderCode', type: 'a-input', maxlength: 30 },
      {
        label: '合同状态',
        prop: 'contractStatusList',
        type: 'a-select',
        options: pageDict.contractStatus,
        attrs: {
          multiple: true,
        },
      },
      {
        label: '业务类型',
        prop: 'orderType',
        type: 'a-select',
        options: pageDict.orderType,
      },
      {
        label: '合同服务类型',
        prop: 'contractTypeList',
        type: 'a-select',
        options: pageDict.contractType,
        attrs: {
          multiple: true,
        },
      },
      {
        label: '承租人类型',
        prop: 'leaseType',
        type: 'a-select',
        options: pageDict.leaseType,
      },
      {
        label: '所属门店',
        prop: 'siteList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
        },
      },
      {
        label: '发起签署时间',
        prop: 'createTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.startTimeStart = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '完成签署时间',
        prop: 'dateRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.completeTimeStart = value[0]
          queryParam.completeTimeEnd = value[1]
        },
      },
      {
        label: '发起人',
        prop: 'startPersonIdList',
        type: 'remote-select',
        attrs: {
          mode: 'multiple',
          type: 'sync_staff_multiple_likeRealname',
        },
      },
      {
        label: '创建方式',
        prop: 'createWay',
        type: 'a-select',
        options: pageDict.createWay,
      },
    ]
  })

  const table = useTable({
    columns: [
      {
        title: '合同编号',
        dataIndex: 'contractNo',
        width: 240,
        fixed: 'left',
      },
      {
        title: '关联单号',
        dataIndex: 'orderCode',
        slotName: 'orderCode',
        width: 240,
      },
      {
        title: '归属门店',
        dataIndex: 'siteName',
        width: 150,
      },
      {
        title: '业务类型',
        dataIndex: 'orderTypeName',
        width: 100,
      },
      {
        title: '合同类型',
        dataIndex: 'contractTypeName',
        width: 100,
      },
      {
        title: '合同模板名称',
        dataIndex: 'templateName',
        width: 150,
      },
      {
        title: '客户类型',
        dataIndex: 'leaseTypeName',
        width: 100,
      },
      {
        title: '客户信息',
        dataIndex: 'lesseeName',
        slotName: 'lesseeName',
        width: 100,
      },
      {
        title: '收费标准',
        dataIndex: 'chargeAmount',
        unit: '元',
        width: 110,
      },
      {
        title: '创建方式',
        dataIndex: 'createWayName',
        width: 100,
      },
      {
        title: '创建节点',
        dataIndex: 'createNode',
        width: 100,
      },
      {
        title: '发起节点',
        dataIndex: 'startNode',
        width: 100,
      },
      {
        title: '合同状态',
        dataIndex: 'contractStatus',
        slotName: 'contractStatus',
        width: 100,
      },
      {
        title: '创建合同时间',
        dataIndex: 'createTime',
        width: 170,
      },
      {
        title: '发起签署时间',
        dataIndex: 'startTime',
        width: 170,
      },
      {
        title: '截止时间',
        dataIndex: 'deadline',
        width: 170,
      },
      {
        title: '完成签署时间',
        dataIndex: 'finishTime',
        slotName: 'finishTime',
        width: 170,
      },
      {
        title: '发起人',
        dataIndex: 'startPersonName',
        width: 100,
      },
    ],
    operates: [
      {
        label: '生成电子合同',
        span: 2,
        show: (record: any) => record.contractStatus == -2,
        permission: 'svms:business:contract:sign.create',
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '关闭',
            okText: '确认',
            content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
            onOk: () => {
              // 一.if企业,有无手机号
              if (record.leaseType == 1) {
                // 企业
                // 查询企业信息(是否包含手机号)
                getDetail({ id: record.lesseeId }).then((res: any) => {
                  clientData.value = res.result
                  if (res.result.mobile && res.result.linkman) {
                    // 1.有企业手机号
                    contractGet(record)
                  } else {
                    // 2.没有企业手机号, 发起手机号填写弹窗
                    addPhonesRef.value.show(record, 'c', clientData.value)
                  }
                })
              } else {
                // 个人
                contractGet(record)
              }
            },
          })
        },
      },
      {
        label: '重新生成',
        show: (record: any) => record.contractStatus == -1,
        permission: 'svms:business:contract:sign.recreate',
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '关闭',
            okText: '确认',
            content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
            onOk: () => {
              if (record.createWay === 2) {
                getOrderDetail(record)
              } else {
                contractGet(record)
              }
            },
          })
        },
      },
      {
        label: '预览',
        permission: 'svms:business:contract:sign.preview',
        show: (record: any) =>
          record.contractStatus != 9 &&
          record.contractStatus != 10 &&
          record.contractStatus != 11 &&
          record.contractStatus != -1 &&
          record.contractStatus != -2,
        method: (record: any) => {
          request
            .post(
              '/svmsContract/downloadContractFile',
              {
                id: record.id,
              },
              {
                responseType: 'blob',
              }
            )
            .then((res) => {
              console.log(res)
              const binaryData = []
              binaryData.push(res.data)
              let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
              // Object.assign(pdfViewInfo, {
              //   url,
              //   title: record.contractTypeName + record.contractNo,
              //   show: true,
              // })
              window.open(url)
            })
        },
      },
      {
        label: '无需签署',
        permission: 'svms:business:contract:sign.invalid',
        show: (record: any) => record.contractStatus === 1 || record.contractStatus == -1 || record.contractStatus == -2,
        method: (record: any) => {
          console.log(record)
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认当前合同是否无需签署，无需签署的合同将变为无效状态，并且当前合同不会重新生成`,
            onOk: () => {
              invalidAPI({ id: record.id }).then((res: any) => {
                console.log(res)
                Message.success('操作成功')
                init()
              })
            },
          })
        },
      },
      {
        label: '发起签署',
        permission: 'svms:business:contract:sign.start',
        show: (record: any) => record.contractStatus === 1,
        method: (record: any) => {
          console.log(record)
          // 一.if企业,有无手机号
          if (record.leaseType == 1) {
            // 企业
            // 查询企业信息(是否包含手机号)
            getDetail({ id: record.lesseeId }).then((res: any) => {
              clientData.value = res.result
              if (res.result.mobile && res.result.linkman) {
                // 1.有企业手机号
                // ①判断余额(接口判断)
                determineAPI({ orderNo: record.orderCode, orderType: record.orderType }).then((res: any) => {
                  if (res.result.determine) {
                    // 1.足够
                    initiateFn(record)
                  } else {
                    // 2.不够
                    Modal.confirm({
                      title: '提示',
                      simple: true,
                      hideCancel: true,
                      okText: '关闭',
                      content: `账户余额不足，请先联系工作人员充值，再进行操作`,
                    })
                    return false
                  }
                })
              } else {
                // 2.没有企业手机号, 发起手机号填写弹窗
                addPhonesRef.value.show(record, 'a', clientData.value)
              }
            })
          } else {
            // 个人
            // 二.判断余额
            determineAPI({ orderNo: record.orderCode, orderType: record.orderType }).then((res: any) => {
              if (res.result.determine) {
                // 1.足够
                initiateFn(record)
              } else {
                // 2.不够
                Modal.confirm({
                  title: '提示',
                  simple: true,
                  hideCancel: true,
                  okText: '关闭',
                  content: `账户余额不足，请先联系工作人员充值，再进行操作`,
                })
                return false
              }
            })
          }
        },
      },
      {
        label: '去签署',
        permission: 'svms:business:contract:sign.sign',
        show: (record: any) =>
          record.contractStatus === 2 && record.signWay === 1 && record.lesseeSignStatus == 2 && record.hireSignStatus == 1,
        method: (record: any) => {
          console.log(record)
          // signWay 0自动 1手动
          // if (record.signWay == 0) {
          //   loadData()
          // } else {
          //   openLinksRef.value.show(record)
          // }
          getTenantSignUrlAPI({ id: record.id }).then((res: any) => {
            window.open(res.result)
          })
        },
      },
      {
        label: '下载',
        permission: 'svms:business:contract:sign.download',
        show: (record: any) => record.contractStatus === 3 || record.contractStatus === 7 || record.contractStatus === 10,
        method: (record: any) => {
          console.log(record)
          request
            .post(
              '/svmsContract/downloadContractFile',
              {
                id: record.id,
              },
              {
                responseType: 'blob',
              }
            )
            .then((res) => {
              console.log(res)
              fileDownload(res.data, record)
            })
        },
      },
      {
        label: '撤回',
        permission: 'svms:business:contract:sign.revoke',
        show: (record: any) => record.contractStatus === 2,
        method: (record: any) => {
          console.log(record)
          if (record.lesseeSignStatus == 1 || record.hireSignStatus == 1) {
            Modal.confirm({
              title: '提示',
              simple: true,
              cancelText: '取消',
              okText: '确认',
              content: `合同撤回后，承租方短信失效，无法完成签署，确认撤回吗？`,
              onOk: () => {
                revokeAPI({ id: record.id }).then(() => {
                  Message.success('操作成功')
                  init()
                })
              },
            })
          } else if (record.orderStatus == -100 || record.orderStatus == -1000) {
            revokeAPI({ id: record.id }).then(() => {
              Message.success('操作成功')
              init()
            })
          }
        },
      },
      {
        label: '发起作废',
        permission: 'svms:business:contract:sign.nullify',
        show: (record: any) => record.contractStatus === 3,
        method: (record: any) => {
          console.log(record)
          // 一.if企业,有无手机号
          if (record.leaseType == 1) {
            // 企业
            // 查询企业信息(是否包含手机号)
            getDetail({ id: record.lesseeId }).then((res: any) => {
              clientData.value = res.result
              if (res.result.mobile && res.result.linkman) {
                // 1.有企业手机号
                nullifyFn(record)
              } else {
                // 2.没有企业手机号, 发起手机号填写弹窗
                addPhonesRef.value.show(record, 'b', clientData.value)
              }
            })
          } else {
            nullifyFn(record)
          }
        },
      },
      {
        label: '去作废',
        permission: 'svms:business:contract:sign.void',
        show: (record: any) =>
          record.signWay === 1 && record.contractStatus === 7 && record.lesseeInvalidedStatus === 2 && record.hireInvalidedStatus === 1,
        method: (record: any) => {
          console.log(record)
          getTenantSignUrlAPI({ id: record.id }).then((res: any) => {
            window.open(res.result)
          })
        },
      },
    ],
    buttons: [
      {
        mode: 'export',
        permission: 'svms:business:contract:sign.export',
        label: '导出',
        method: () => handleExport(),
      },
    ],
  })

  // 导出事件
  const handleExport = () => {
    useExport(exportContractAuthRecord, queryParam)
  }

  // 列表里点击失败原因
  const errorShow = (record: any) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      Modal.confirm({
        title: '提示',
        simple: true,
        hideCancel: true,
        okText: '关闭',
        content: record.createErrorReason,
      })
    }
  }

  // 去修改订单
  const toError = (record: any) => {
    Modal.confirm({
      title: '合同生成失败',
      simple: true,
      cancelText: '关闭',
      okText: '前往修改',
      content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
      onOk: () => {
        if (record.orderType === 1) {
          navigateTo(`/short-order/edit/${record.orderId}`, `${record.orderCode}-修改订单`)
        } else {
          navigateTo(`/long-order/edit/${record.orderId}`, `${record.orderCode}-修改订单`)
        }
      },
    })
  }

  // 发起签署
  const initiateFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `请确认是否要发起合同签署?`,
      onOk: () => {
        // 发起签署接口
        initiateAPI({ id: record.id }).then((res: any) => {
          console.log(res)
          if (res.code == 200) {
            // 企业/个人 提示不同
            if (record.leaseType == 1) {
              // 企业
              Modal.confirm({
                title: '提示',
                simple: true,
                hideCancel: true,
                okText: '关闭',
                content: `已将合同信息以短信的形式发送至企业联系人手机，并等待签署`,
                onOk: () => {
                  init()
                },
              })
            } else {
              // 个人
              Modal.confirm({
                title: '提示',
                simple: true,
                hideCancel: true,
                okText: '关闭',
                content: `已将合同信息以短信的形式发送至承租人手机，并等待签署`,
                onOk: () => {
                  init()
                },
              })
            }
          }
        })
      },
    })
  }

  // 发起作废
  const nullifyFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `合同已完成签署，确认作废吗?`,
      onOk: () => {
        // 发起作废接口
        nullifyAPI({ id: record.id }).then((res: any) => {
          console.log(res)
          if (res.code == 200) {
            // 企业/个人 提示不同
            if (record.leaseType == 1) {
              // 企业
              Modal.confirm({
                title: '提示',
                simple: true,
                hideCancel: true,
                okText: '关闭',
                content: `已将作废协议以短信形式发送至企业联系人手机，并等待签署`,
                onOk: () => {
                  init()
                },
              })
            } else {
              // 个人
              Modal.confirm({
                title: '提示',
                simple: true,
                hideCancel: true,
                okText: '关闭',
                content: `已将作废协议以短信形式发送至承租人手机，并等待签署`,
                onOk: () => {
                  init()
                },
              })
            }
          }
        })
      },
    })
  }

  const onLink = (record: any) => {
    if (record.orderType == 1) {
      navigateTo(`/short-order/detail/${record.orderId}`, `${record.orderCode}-短租详情`)
    } else if (record.orderType == 2) {
      navigateTo(`/long-order/detail/${record.orderId}`, `${record.orderCode}-长租详情`)
    }
  }

  // 文件下载
  const fileDownload = (_res: any, record: any) => {
    let blob = new Blob([_res], { type: 'application/pdf' })
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) //创建下载的链接
    downloadElement.href = href
    // downloadElement.download = fileName; //下载后文件名
    downloadElement.download = downloadElement.download = record.contractTypeName + record.contractNo //下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
    window.URL.revokeObjectURL(href) //释放掉blob对象
  }

  // 签署弹窗点确定
  const openlinkFn = () => {
    init()
  }

  // 带回电话
  const addphoneFn = (recordData: any) => {
    console.log('recordData-----------', recordData)
    // 补充电话
    if (recordData.type == 'a') {
      // 调用发起签署补充电话的接口(编辑企业客户接口)
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 判断余额
        determineAPI({ orderNo: recordData.orderCode, orderType: recordData.orderType }).then((res: any) => {
          if (res.result.determine) {
            // 1.足够
            // 发起签署
            initiateFn(recordData.record)
          } else {
            // 2.不够
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `账户余额不足，请先联系工作人员充值，再进行操作`,
            })
            return false
          }
        })
      })
    }
    if (recordData.type == 'b') {
      // 调用发起作废补充电话的接口
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 发起作废
        nullifyFn(recordData.record)
      })
    }
    if (recordData.type == 'c') {
      // 调用生成电子合同补充电话的接口
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 生成电子合同
        contractGet(recordData.record)
      })
    }
  }

  const onCopy = (record: any, message?: any) => {
    getContractTenantSignUrl({ id: record.id }).then((res: any) => {
      copy(res.result, message)
    })
  }

  const headerConfig = ref()
  // 获取签署记录表头统计
  const getContractSignRecordHeader = () => {
    contractSignRecordHeader(queryParam).then((res) => {
      headerConfig.value = res.result
    })
  }

  // 签署记录统计
  const getContractSignRecordCount = () => {
    contractSignRecordCount(queryParam).then((res) => {
      console.log(res, 'res')
      const result = res.result
      result.forEach((item: any) => {
        quickSearchData.value.forEach((i: any) => {
          if (i.key == item.contractStatus) {
            i.value = item.contractCount
          }
        })
      })
    })
  }

  // 生成合同
  const contractGet = (record: any) => {
    createQysContractAPI({ id: record.id }).then((res: any) => {
      console.log(res)
      if (res.result.createErrorCode) {
        if (res.result.createErrorCode == 1001) {
          // 生成失败弹窗
          // 1. 姓名手机号不匹配时
          toError(record)
        } else {
          // 生成失败弹窗
          // 2. 其他原因（没有前往修改按钮）
          Modal.confirm({
            title: '提示',
            simple: true,
            hideCancel: true,
            okText: '关闭',
            content: res.result.createErrorReason,
          })
          init()
        }
      } else if (res.result.createErrorCode == null) {
        Message.success('操作成功')
        init()
      }
    })
  }

  const searcherReset = () => {
    quickSearchData.value.forEach((i: any) => {
      i.checked = false
    })
    queryParam.contractStatusList = []
    getContractSignRecordHeader()
  }

  const improveInformationRef = ref()
  const onClick = (detail: any) => {
    if (!isMobile(detail.memberPhone)) {
      Message.error('承租人手机号格式不正确，请修改正确后，再生成电子合同')
      return
    } else if (detail.orderStatus === 10) {
      Message.error('请先完成订单的排车，再生成电子合同')
      return
    } else if (!detail.carLicenseNo) {
      modalAlert.value = '当前渠道订单的已排车辆未与启程系统的车辆进行匹配，请先完成车辆匹配后，再生成电子合同'
      type.value = 'person'
      improveInformationRef.value.onOpen(detail)
      return
    } else if (detail.memberType === 1) {
      getDetail({ id: detail.clientId }).then((res: any) => {
        const result = res.result
        if (!result.linkman || !result.mobile) {
          modalAlert.value = '请先完善企业联系人信息，再生成电子合同'
          type.value = 'business'
          detail = { ...detail, ...{ business: result } }
          improveInformationRef.value.onOpen(detail)
        } else {
          viewVisible.value = true
        }
      })
      return
    } else {
      viewVisible.value = true
    }
  }

  const onOk = (options: any) => {
    viewLoading.value = true

    const { detail } = options
    createContractAPI({
      orderType: detail.orderType,
      orderCode: detail.orderCode,
      contractType: 1,
      id: detail?.contractId,
      operationType: detail?.operationType,
    })
      .then((res: any) => {
        console.log(res)
        if (res.result.createErrorCode) {
          viewVisible.value = false
          if (res.result.createErrorCode == 1001) {
            // 生成失败弹窗
            // 1. 姓名手机号不匹配时
            toError({ orderCode: detail.orderCode })
          } else {
            // 生成失败弹窗
            // 2. 其他原因（没有前往修改按钮）
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: res.result.createErrorReason,
            })
            init()
          }
        } else if (res.result.createErrorCode == null) {
          Message.success('操作成功')
          init()
          viewVisible.value = false
        }
      })
      .finally(() => {
        viewLoading.value = false
      })
  }

  const loadData = useFetchTableDataApi(table, queryParam, getContractSignRecord)

  const orderDetails = ref()
  const getOrderDetail = (record: any) => {
    getShortOrdrDetails({ id: record.id }).then((res: any) => {
      orderDetails.value = {
        ...res.result.orderInfo,
        ...{
          contractId: record.id,
          operationType: 1,
          orderType: record.orderType,
          orderId: record.orderId,
          contractType: record.contractType,
        },
      }
      onClick(orderDetails.value)
    })
  }

  const init = () => {
    loadData()
    getContractSignRecordHeader()
    getContractSignRecordCount()
  }

  const initLoadData = () => {
    loadData()
    getContractSignRecordCount()
  }

  onMounted(() => {
    loadData()
    getContractSignRecordHeader()
    getContractSignRecordCount()
  })

  /**
   * 复制
   * @param value 复制的值
   */
  const copy = async (value: any, message = '复制成功') => {
    try {
      await toClipboard(value)
      Message.success(message)
    } catch (error) {
      Message.error('复制失败')
    }
  }
</script>

<style lang="less" scoped>
  .service-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 500px;

    &-img {
      width: 86px;
      height: 129px;
      margin-bottom: 27px;
    }

    &-text {
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
    }
  }

  .page-container {
    padding-top: 0;
    .quick-search {
      display: flex;
      margin-bottom: 20px;

      &-item {
        width: 16%;
        height: 62px;
        padding: 9px 0 9px 16px;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #e5e8ef;
        cursor: pointer;

        &:hover {
          transform: scale(1.1);
          transition: transform 0.3s;
          position: relative;
          z-index: 999;
        }

        &-checked {
          background: #e8f3ff;
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #1890ff;
        }

        &:nth-of-type(n + 2) {
          margin-left: 20px;
        }

        &-label {
          font-size: 12px;
          font-weight: 400;
          color: #4e5969;
        }

        &-value {
          font-size: 20px;
          font-weight: 600;
          color: #1d2129;

          &-checked {
            color: #1890ff;
          }
        }
      }
    }

    .table-summary-box {
      padding: 20px 20px;
      margin-bottom: 20px;
      background: #f7f8fa;

      .table-info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        &-item {
          margin-right: 20px;
          span {
            color: #1890ff;
          }
        }
      }
    }

    .status {
      font-size: 14px;
      font-weight: 400;
      color: rgba(185, 187, 196, 1);

      &.status-unauth {
        color: rgba(185, 187, 196, 1);
      }
      &.status-signing {
        color: rgba(52, 145, 250, 1);
      }
      &.status-success {
        color: rgba(0, 180, 42, 1);
      }
      &.status-finish {
        color: rgba(245, 63, 63, 1);
      }

      &.status-failed {
        color: rgba(255, 125, 0, 1);
      }
      &.status-invalid {
        color: rgba(114, 46, 209, 1);
      }
    }

    .block {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      height: 20px;
      padding: 0 8px;
      font-size: 12px;
      font-weight: 500;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid;

      &.block-unsign {
        color: rgba(255, 125, 0, 1);
        border-color: rgba(255, 125, 0, 1);
        background-color: rgba(255, 247, 232, 1);
      }

      &.block-signed {
        color: rgba(0, 180, 42, 1);
        border-color: rgba(0, 180, 42, 1);
        background-color: rgba(232, 255, 234, 1);
      }
    }
  }
</style>
